package com.atguigu.gmall.common.service;

import com.atguigu.gmall.common.entity.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

@Component
public class RabbitService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    //发送普通消息
    public void sendMessage(String exchange,String routingKey,Object message){
        GmallCorrelationData correlationData = getGmallCorrelationData(exchange, routingKey, message);
        rabbitTemplate.convertAndSend(exchange,routingKey,message,correlationData);
    }

    //发送死信消息
    public void sendDeadLetterMessage(String exchange,String routingKey,Object message,int delayTime){
        GmallCorrelationData correlationData = getGmallCorrelationData(exchange, routingKey, message);
        //延迟消息
        correlationData.setDelay(true);
        //延迟时间
        correlationData.setDelayTime(delayTime);
        rabbitTemplate.convertAndSend(exchange,routingKey,message,message1 -> {
            //设置过期时间  基于死信
            System.out.println("发送死信消息的时间：" + new Date());
            message1.getMessageProperties().setExpiration(String.valueOf(delayTime * 1000));
            return message1;
        },correlationData);
    }

    //发送延迟消息(基于插件)
    public void sendDelayMessage(String exchange,String routingKey,Object message,int delayTime){
        GmallCorrelationData correlationData = getGmallCorrelationData(exchange, routingKey, message);
        //延迟消息
        correlationData.setDelay(true);
        //延迟时间
        correlationData.setDelayTime(delayTime);
        rabbitTemplate.convertAndSend(exchange,routingKey,message,message1 -> {
            //设置过期时间  基于插件
            System.out.println("发送延迟消息的时间：" + new Date());
            message1.getMessageProperties().setDelay(delayTime * 1000);
            return message1;
        },correlationData);
    }


    private GmallCorrelationData getGmallCorrelationData(String exchange, String routingKey, Object message) {
        GmallCorrelationData correlationData = new GmallCorrelationData();
        String uuid = UUID.randomUUID().toString();
        correlationData.setId(uuid);
        correlationData.setMessage(message);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        return correlationData;
    }
}
